<?php

namespace Biz\service\brand;

use Biz\model\brand\Brand as mBrand;
use Biz\model\brand\BrandOrder;
use Biz\model\brand\BrandPackage;
use Biz\model\brandAccount\BrandAccountAuth;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\model\brandAccount\BrandAccountShop;
use Biz\pockets\serviceTrait\_Async;
use Biz\service\brandPack\RenewPackageService;
use Biz\service\BrandRights\BrandRightsAllService;
use Biz\service\trade\Pay;
use Doraemon\cache\User as cUser;
use Doraemon\cache\UserAuthStatus as cUserAuthStatus;
use Doraemon\model\Member as mMember;
use Doraemon\model\Phone;
use Doraemon\service\DingTalkAlert;
use Doraemon\service\Follow as sFollow;
use Doraemon\service\Member;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use hhz\constant\basic\findPhoneScene;

/**
 * 品牌订单服务类
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */
class Order
{
    use _Async;

    const PAY_PLATFORM_ALIPAY = 1; //支付宝
    const PAY_PLATFORM_WECHAT = 2; //微信支付

    /**
     * 支付
     * @param $uid
     * @param $order_sn
     * @param $pay_platform
     * @param null $payStopTime
     * @return bool
     */
    public static function pay($uid, $order_sn, $pay_platform, $payStopTime = 0)
    {
        $result_order_info = BrandOrder::getOrder($order_sn);

        if (empty($result_order_info)) {
            Log::error("function:pay#error:order#支付方式:{$pay_platform}#uid:{$uid}#order_sn:{$order_sn}#", $result_order_info);

            return false;
        }

        $orderInfo = [
            // 订单号
            'order_no' => $order_sn,
            // 支付金额
            'pay_amount' => $result_order_info['price'],
            // 付款详情标题
            'title' => $result_order_info['package_name'],
        ];
        if (!empty($payStopTime) && !is_null($payStopTime)) {
            $orderInfo['paystop_time'] = $payStopTime;
        }

        try {
            switch ($pay_platform) {
                case self::PAY_PLATFORM_ALIPAY:
                    // 支付宝扫码
                    $pay_url = Pay::getPayOrderInfo($orderInfo, Pay::_PAY_WAYS_ALIPAY_QRCODE, Pay::_PAY_ORDER_TYPE_BRAND);
                    break;
                case self::PAY_PLATFORM_WECHAT:
                    // 微信扫码
                    $pay_url = Pay::getPayOrderInfo($orderInfo, Pay::_PAY_WAYS_WECHAT_BIZ_QRCODE, Pay::_PAY_ORDER_TYPE_BRAND);
                    break;
            }
        } catch (\Exception $e) {
            Log::error("function:pay#error:Exception#支付方式:{$pay_platform}#uid:{$uid}#order_sn:{$order_sn}#pay_amount:{$result_order_info['price']}#title:{$result_order_info['package_name']}", $e);

            return false;
        }

        if (!empty($pay_url)) {
            $qr_code_url = ImgUrl::getQrcode($pay_url);
            Log::info("function:pay#支付方式:{$pay_platform}#uid:{$uid}#order_sn:{$order_sn}#pay_amount:{$result_order_info['price']}#title:{$result_order_info['package_name']}#支付二维码:{$qr_code_url}", $orderInfo);

            return $qr_code_url;
        } else {
            Log::error("function:pay#error:pay_other#支付方式:{$pay_platform}#uid:{$uid}#order_sn:{$order_sn}#pay_amount:{$result_order_info['price']}#title:{$result_order_info['package_name']}", $pay_platform);

            return false;
        }
    }

    /**
     * 创建订单
     * @param $orderType
     * @param $uid
     * @param $brand_id
     * @param $package_id
     * @param $pay_platform
     * @param $pack_type
     * @param $price
     * @param $inStartTime
     * @param $inEndTime
     * @param $remark
     * @param $adminId
     * @return array|bool
     */
    public static function createOrder($orderType, $uid, $brand_id, $package_id, $pay_platform, $pack_type, $price, $inStartTime, $inEndTime, $remark = '', $adminId = 0)
    {
        $brand_info = mBrand::getInfo($brand_id);
        $package_info = BrandPackage::getById($package_id);
        $productPrice = $package_info['price'];
        $order_sn = OrderSN::createOrderSN($uid);
        $result = BrandOrder::createOrder(
            $orderType,
            $order_sn,
            $uid,
            $brand_id,
            $brand_info['brand_name'],
            $package_id,
            $package_info['package_name'],
            $pay_platform,
            $price,
            $productPrice,
            $pack_type,
            $inStartTime,
            $inEndTime,
            $remark,
            $adminId
        );

        if ($result) {
            return [
                $order_sn,
                $package_info['package_name'],
                $price,
            ];
        }
        return false;
    }

    /**
     * 检查支付状态
     * @param $order_sn
     * @return bool
     */
    public static function checkPay($order_sn)
    {
        $order_info = BrandOrder::getOrder($order_sn);

        if (!empty($order_info) && $order_info['pay_status'] == BrandOrder::PAY_STATUS_PAID) {
            Log::info("function:checkPay#action:checkPay_select#order_sn:{$order_sn}", $order_info);

            return true;
        } elseif (!empty($order_info)) {
            // 查询支付结果
            $result = Pay::checkOrderPayStatus($order_sn, Pay::_PAY_ORDER_TYPE_BRAND);
            Log::info("function:checkPay#action:checkOrderPayStatus#order_sn:{$order_sn}#result:{$result}", $result);

            return $result ? true : false;
        } else {
            return false;
        }
    }

    /**
     * 是否为延时订单
     * @param $orderInfo
     * @return bool
     */
    public static function isDelayedOrder($orderInfo)
    {
        $isDelayedOrder = false;
        if ($orderInfo['in_start_time'] > date('Y-m-d')) {//延时订单
            $isDelayedOrder = true;
        }
        return $isDelayedOrder;
    }

    /**
     * 支付成功回调
     * @param $order_sn
     * @param $other_sn
     * @param $pay_platform
     * @param $amount
     * @param $pay_time
     * @return bool
     * @throws \Exception
     */
    public static function callbackPaySuccess($order_sn, $other_sn, $pay_platform, $amount, $pay_time)
    {
        Log::info('#brand#callbackPaySuccess', [$order_sn, $other_sn, $pay_platform, $amount, $pay_time]);
        $order_info = BrandOrder::getOrder($order_sn);

        if (!empty($order_info) && $order_info['pay_status'] == BrandOrder::PAY_STATUS_PAID) {
            return true;
        }

        if ($pay_platform == Pay::_PAY_WAYS_ALIPAY_QRCODE) {
            $pay_platform = self::PAY_PLATFORM_ALIPAY;
        } elseif ($pay_platform == Pay::_PAY_WAYS_WECHAT_BIZ_QRCODE) {
            $pay_platform = self::PAY_PLATFORM_WECHAT;
        }
        $isDelayedOrder = self::isDelayedOrder($order_info);
        //延时订单，服务状态为未开通
        $orderServiceStatus = $isDelayedOrder ? BrandOrder::SERVICE_STATUS_UNFINISHED : BrandOrder::SERVICE_STATUS_FINISHED;
        $result = BrandOrder::updatePayStatus(
            $order_sn,
            $other_sn,
            BrandOrder::PAY_STATUS_PAID,
            strtotime($pay_time),
            $pay_platform,
            $amount,
            BrandOrder::ORDER_STATUS_FINISHED,
            $orderServiceStatus,
        );

        Log::info('#brand#callbackPaySuccess_result', [$order_info['brand_id'], $order_info['pack_type'], $order_info['package_id'], $order_sn, $other_sn, $pay_platform, $amount, $pay_time, $result]);
        if ($isDelayedOrder) {//延时订单
            RenewPackageService::createRenewPackage($order_info['brand_id'], $order_info['package_id'], $order_info['id'], $order_info['in_start_time'], $order_info['in_end_time']);
        } else {
            self::afterStartBrandAccount($order_info);
            BrandRightsAllService::afterBrandOrder($order_info);
            if (!HhzEnv::isTest() && !HhzEnv::isGray()) {
                self::sendOrderMsg($order_info, $amount, $pay_platform, $pay_time);
            }
        }

    }

    /**
     * 开始入驻的品牌订单,品牌账户处理
     * @param $orderInfo 订单信息
     * @param false $isDelayed 是否为延迟订单
     */
    public static function afterStartBrandAccount($orderInfo, $isDelayed = false)
    {
        $brandId = $orderInfo['brand_id'];
        $packType = $orderInfo['pack_type'];
        $packageId = $orderInfo['package_id'] ?? 0;
        $brandInfo = mBrand::getInfo($brandId);

        if ($isDelayed) {//延时订单，更改服务状态
            BrandOrder::update(['service_status' => BrandOrder::SERVICE_STATUS_FINISHED], ['dsn' => $orderInfo['dsn']]);
        }

        $brandAccount = BrandAccountInfo::getOneByWhere([
            'brand_id' => $brandId,
            'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
            'account_status[!]' => BrandAccountInfo::ACCOUNT_STATUS_DEL
        ]);
        $brandType = $brandAccount['brand_type'];
        $nick = $brandAccount['nick'];
        if (in_array($brandType, [mBrand::BRAND_TYPE_DEFAULT, mBrand::BRAND_TYPE_EXPIRE])) {
            $brandType = mBrand::BRAND_TYPE_COMMON;
        }

        $useAuth = false;
        if ($isDelayed) {
            $brandType = mBrand::BRAND_TYPE_COMMON;
            $useAuth = true;
        } else if ($brandAccount['account_status'] != BrandAccountInfo::ACCOUNT_STATUS_USED) {
            $useAuth = true;
        }
        $accountData['in_start_time'] = $orderInfo['in_start_time'];
        $accountData['in_end_time'] = $orderInfo['in_end_time'];
        $accountData['brand_type'] = $brandType;
        $accountData['account_status'] = BrandAccountInfo::ACCOUNT_STATUS_USED;
        $accountData['auth_status'] = BrandAccountInfo::AUTH_STATUS_USED;
        $authInfo = BrandAccountAuth::getOneByWhere(['account_id' => $brandAccount['id'], 'auth_status' => BrandAccountAuth::AUTH_STATUS_PASS]);
        if ($authInfo && $useAuth) {
            $nick = $authInfo['nick'];
            $accountData['nick'] = $authInfo['nick'];
        }
        BrandAccountInfo::updateData($accountData, ['id' => $brandAccount['id']]);
        if ($useAuth) {
            BrandAccountAuth::updateData([
                'auth_status' => BrandAccountAuth::AUTH_STATUS_EXPIRE
            ], [
                'account_id' => $brandAccount['id'],
                'auth_status' => BrandAccountAuth::AUTH_STATUS_USED
            ]);
            BrandAccountAuth::updateData([
                'auth_status' => BrandAccountAuth::AUTH_STATUS_USED
            ], [
                'account_id' => $brandAccount['id'],
                'auth_status' => BrandAccountAuth::AUTH_STATUS_PASS
            ]);
            $shopList = $authInfo ? json_decode($authInfo['shop'], true) : [];
            if (is_array($shopList)) {
                $addIds = [];
                foreach ($shopList as $row) {
                    if ($row['shop_id']) {
                        $data = [
                            'account_id' => $brandAccount['id'],
                            'type' => $row['type'],
                            'other_type' => $row['other_type'] ?? 0,
                            'name' => $row['name'],
                            'url' => $row['url'],
                            'shop_id' => $row['shop_id'],
                            'letter' => $row['letter'],
                            'authorization' => $row['authorization'],
                            'shop_status' => BrandAccountShop::SHOP_STATUS_VALID,
                            'admin_id' => 0
                        ];
                        $shopInfo = BrandAccountShop::getOneByWhere(['account_id' => $brandAccount['id'], 'shop_id' => $row['shop_id'], 'type' => $row['type']]);
                        if ($shopInfo) {
                            BrandAccountShop::updateData($data, ['id' => $shopInfo['id']]);
                            $addIds[] = $shopInfo['id'];
                        } else {
                            $accountShopId = BrandAccountShop::insertData($data);
                            if ($accountShopId) {
                                $addIds[] = $accountShopId;
                            }
                        }
                    }
                }
                if ($addIds && $brandAccount['id']) {
                    BrandAccountShop::updateData(['shop_status' => BrandAccountShop::SHOP_STATUS_NOVALID], ['id[!]' => $addIds, 'account_id' => $brandAccount['id']]);
                }
            }
        }

        //审核通过，修改品牌关联的uid

        mBrand::update(['pack_type' => $packType, 'brand_type' => $brandType, 'status' => mBrand::STATUS_USING, 'package_id' => $packageId], ['id' => $brandId]);

        $memberData = [
            'type' => mMember::AUTH_USER_BRAND,
            'status' => mMember::STATUS_NORMAL,
        ];
        $result = Member::nick(false,true, $nick, $brandAccount['uid'], mMember::AUTH_USER_BRAND,
        true, true, true, true);
        if ($result === true || $result === '30天之内只能修改一次用户名' || $result === '该昵称已被占用') {
            $memberData['nick'] = $nick;
        }
        //更新主账户类别，普通用户改变类别，品牌用户不用改变类别
        mMember::updateUserInfo($brandAccount['uid'], $memberData);
        cUser::deleteUserInfo($brandAccount['uid']);
        sFollow::autoBrandFollow($brandAccount['uid']);
        // 标记用户强制退出
        cUserAuthStatus::setAuthType($brandAccount['uid'], mMember::AUTH_USER_BRAND);
    }

    /**
     * 发送订单消息通知
     * @param $orderInfo
     * @param $amount
     * @param $payPlatform
     * @param $payTime
     */
    public static function sendOrderMsg($orderInfo, $amount, $payPlatform, $payTime)
    {
        if ($orderInfo) {
            self::_async($orderInfo, $amount, $payPlatform, $payTime);
        }
    }

    public static function _async_sendOrderMsg($orderInfo, $amount, $payPlatform, $payTime)
    {
        $phone = Phone::getDecryptPhoneByUid($orderInfo['uid'], findPhoneScene::SHOP_ORDER_PHONE);

        //钉钉机器人消息通知
        DingTalkAlert::sendTextMsg(
            DingTalkAlert::BRAND_PAY_KEY,
            implode("\n", [
                "品牌id：{$orderInfo['brand_id']}",
                "品牌名称：{$orderInfo['brand_name']}",
                "关联账户uid：{$orderInfo['uid']}",
                "手机号：{$phone}",
                "金额：{$amount}",
                "付费方式：" . ($payPlatform == 1 ? '支付宝' : '微信'),
                "付费时间：{$payTime}",
            ]),
            true
        );

        //钉钉机器人消息通知
        DingTalkAlert::sendTextMsg(
            DingTalkAlert::BRAND_SALES,
            implode("\n", [
                "品牌id：{$orderInfo['brand_id']}",
                "品牌名称：{$orderInfo['brand_name']}",
                "关联账户uid：{$orderInfo['uid']}",
                "手机号：{$phone}",
                "金额：{$amount}",
                "付费方式：" . ($payPlatform == 1 ? '支付宝' : '微信'),
                "付费时间：{$payTime}",
            ]),
            true
        );
    }


}
